package cn.qdhlm.frontendprocessor.common.helper;

import lombok.extern.log4j.Log4j2;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @Name: MqttHelper
 * @Description: MqttHelper
 * @Author: jiangcs
 */
@Log4j2
@Component
public class MqttHelper {
//    @Resource

    @Autowired
    private MqttAsyncClient mqttClient;
    private static MqttAsyncClient mqttClientSta;

    @PostConstruct
    private void init() {
        mqttClientSta = this.mqttClient;
    }

    /**
     * 发布，默认qos为0，非持久化
     *
     * @param topic
     * @param byteArray
     */
    public static boolean publish(String topic, byte[] byteArray) {
        return publish(0, false, topic, byteArray);
    }

    /**
     * 发布
     *
     * @param qos
     * @param retained
     * @param topic
     * @param byteArray
     */
    public static boolean publish(int qos, boolean retained, String topic, byte[] byteArray) {
        if ("".equals(topic) || null == topic) {
            log.error("topic is empty");
            return false;
        }

        try {
            MqttMessage message = new MqttMessage();
            message.setQos(qos);
            message.setRetained(retained);
            message.setPayload(byteArray);
            mqttClientSta.publish(topic, message);
            return true;
        } catch (MqttException e) {
            log.error("publish exception", e);
        }
        return false;
    }

    /**
     * 订阅某个主题，qos默认为0
     *
     * @param topic
     */
    public static void subscribe(String topic) {
        subscribe(topic, 0);
    }

    /**
     * 订阅某个主题
     *
     * @param topic
     * @param qos
     */
    public static void subscribe(String topic, int qos) {
        try {
            mqttClientSta.subscribe(topic, qos);
        } catch (MqttException e) {
            log.error("subscribe exception", e);
        }
    }
}
